import re

import requests
from django.http import HttpResponse, StreamingHttpResponse

from public.utils import local_ip
from webpage.mei.urls import register_url


@register_url(re.compile(r'^api/.*$'))
def relay(request):
    """ 转发以api开头的请求到服务端fastapi"""
    upstream = f'http://{local_ip()}:9000{request.path}'  # 目标地址
    method = request.method  # GET/POST/PUT/DELETE...
    headers = {k: v for k, v in request.headers.items() if k.lower() not in {
        'host', 'connection', 'content-length'  # 让 requests 自己处理
    }}
    params = request.GET.dict()  # 查询参数
    data = request.body  # 原始字节（含 JSON/form/文件）

    # 真正转发
    resp = requests.request(
        method,
        upstream,
        headers=headers,
        params=params,
        data=data,
        files=request.FILES,  # 文件也能带
        allow_redirects=False,  # 让客户端自己跟 301/302
        stream=True  # 流式取响应，节省内存
    )

    # 把上游响应原样还给客户端
    django_resp = HttpResponse(
        resp.raw,
        status=resp.status_code,
        content_type=resp.headers.get('Content-Type')
    )
    # 透传关键头
    for k, v in resp.headers.items():
        if k.lower() not in {'content-encoding', 'content-length', 'connection'}:
            django_resp[k] = v
    return django_resp


def relay_stream(request, path):
    # TODO 待适配
    upstream = f'http://your-backend/{path}'
    headers = {k: v for k, v in request.headers.items()
               if k.lower() not in {'host', 'connection'}}
    resp = requests.request(
        request.method,
        upstream,
        headers=headers,
        params=request.GET,
        data=request.body,
        stream=True,
        allow_redirects=False
    )

    # 逐块回传
    django_resp = StreamingHttpResponse(
        streaming_content=(chunk for chunk in resp.iter_content(chunk_size=8192)),
        status=resp.status_code,
        content_type=resp.headers.get('Content-Type')
    )
    for k, v in resp.headers.items():
        if k.lower() not in {'content-encoding', 'connection'}:
            django_resp[k] = v
    return django_resp
